package com.zhugang.week04;

/**
 * @program algorithms
 * @description: reverseList
 * @author: chanzhugang
 * @create: 2022/06/23 23:37
 */
public class ReverseList {

    /**
     * 剑指offer 24 反转链表
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        // 开辟新链表，每次遍历指针反转：p.next = new; new = p;
        ListNode newNode = null;
        ListNode p = head;
        while (p != null) {
            ListNode temp = p.next;
            p.next = newNode;
            newNode = p;
            p = temp;
        }
        return newNode;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}